﻿// -----------------------------------------------------------------------------
// 园丁,是个很简单的管理系统
//  gitee:https://gitee.com/hgflydream/Gardener 
//  issues:https://gitee.com/hgflydream/Gardener/issues 
// -----------------------------------------------------------------------------

using Furion.DatabaseAccessor;
using Gardener.Application.Dtos;
using Gardener.Core.Entites;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Threading.Tasks;
using Gardener.Common;
using System.Linq.Expressions;
using Furion.FriendlyException;
using Gardener.Enums;
using Gardener.Core;
using Gardener.Application.Interfaces;
using Furion;

namespace Gardener.Application
{
    /// <summary>
    /// 用户服务
    /// </summary>
    [ApiDescriptionSettings("UserAuthorizationServices")]
    public class CarService : ApplicationServiceBase<Car, CarDto>, ICarsService
    {
        private readonly IRepository<Car> _carRepository;
        private readonly IRepository<Shield> _shieldRepository;
        /// <summary>
        /// 用户服务
        /// </summary>
        /// <param name="carRepository"></param>
        public CarService(
            IRepository<Car> carRepository,
            IRepository<Shield> shieldRepository) : base(carRepository)
        {
            _carRepository = carRepository;
            _shieldRepository = shieldRepository;
        }

        /// <summary>
        /// 搜索用户
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Dtos.PagedList<CarDto>> Search([FromQuery] string name, int pageIndex = 1, int pageSize = 10)
        {
            var cars = _carRepository
              .Where(u => u.IsDeleted == false)
              .Where(!string.IsNullOrEmpty(name), u => u.CarNumber.Contains(name) || u.Company.Contains(name))
              .OrderByDescending(x => x.CreatedTime)
              .Select(u => u.Adapt<CarDto>());
            var pageList = await cars.ToPagedListAsync(pageIndex, pageSize);
            
            return pageList;

        }
        /// <summary>
        /// 更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<bool> Update(CarDto input)
        {
            var car = input.Adapt<Car>();
            car.UpdatedTime = DateTimeOffset.Now;

            List<Expression<Func<Car, object>>> exclude = new List<Expression<Func<Car, object>>>()
            {
                x=>x.CreatedTime
            };
            //更新
            await _carRepository.UpdateExcludeAsync(car, new[] { "CreatedTime" });

            return true;
        }
        /// <summary>
        /// 新增一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<CarDto> Insert(CarDto input)
        {
            if (_shieldRepository.Any(x => x.IsDeleted == false && x.ShieldType != ShieldType.Before && input.CarNumber.Contains(x.ShieldNumber), false))
            {
                throw Oops.Oh(ExceptionCode.CAR_NAME_FORBIDDEN);
            }

            var user = App.GetService<IAuthorizationManager>().GetUser();
            input.ApplyName = user.UserName;
            Car car = input.Adapt<Car>();

            car.CreatedTime = DateTimeOffset.Now;
            var newEntity = await _carRepository.InsertAsync(car);

            return newEntity.Entity.Adapt<CarDto>();
        }

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        public override async Task<CarDto> Get(int id)
        {
            var person = await _carRepository
                .Where(x => x.Id == id)
                .FirstOrDefaultAsync();
            return person.Adapt<CarDto>();
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override async Task<bool> Pass(int id)
        {
            //审核通过
            await _carRepository.UpdateIncludeAsync(new Car
            {
                Id = id,
                IsPass = PassType.Yes,
                UpdatedTime = DateTime.Now
            }, new[] { nameof(Car.IsPass) });

            return true;
        }

        /// <summary>
        /// 放行
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override async Task<bool> Release(int id)
        {
            await _carRepository.UpdateIncludeAsync(new Car
            {
                Id = id,
                IsRelease = true,
                UpdatedTime = DateTime.Now
            }, new[] { nameof(Car.IsRelease) });

            return true;
        }
    }
}
